package com.example.drcbackend.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.drcbackend.Mapper.SubsetdbMapper;
import com.example.drcbackend.Mapper.UserMapper;
import com.example.drcbackend.Mapper.DbMapper;
import com.example.drcbackend.Mapper.attributessetsMapper;
import com.example.drcbackend.entity.Db;
import com.example.drcbackend.entity.Subsetdb;
import com.example.drcbackend.entity.User;
import com.example.drcbackend.entity.attributessets;
import com.example.drcbackend.jwt.JwtUtils;
import com.example.drcbackend.jwt.Result;
import com.example.drcbackend.util.SqlParserUtil;
import com.example.drcbackend.entity.dto.TableSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class FileUploadService {
    @Autowired
    private UserMapper um;
    @Autowired
    private DbMapper dm;
    @Autowired
    private attributessetsMapper am;
    @Autowired
    private SubsetdbMapper sm;


    private static final String UPLOAD_DIR = "E://SQL_test";
    private static final Logger logger = LoggerFactory.getLogger(FileUploadService.class);

    public User getuser(String token) {
        String uname = JwtUtils.getClaimsByToken(token).getSubject();
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getAccount, uname);
        User user = um.selectOne(lqw);
        return user;
    }

    public Result uploadSQLFile(MultipartFile file) {
        // User user = getuser(token);
        Db db = new Db();
        //db.setUserid(user.getId());

        try {
            if (file.isEmpty()) {
                return Result.error().message("上传文件不能为空").code(Result.ERROR);
            }

            File uploadPath = new File(UPLOAD_DIR);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }

            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String dbNameWithoutExtension = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            db.setDbname(dbNameWithoutExtension);

            dm.insert(db);


            String savedFileName = db.getDbid() + fileExtension;

            Path uploadDirectoryPath = Paths.get(UPLOAD_DIR);
            Path filePath = uploadDirectoryPath.resolve(savedFileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            logger.info("文件上传成功：{} -> {}", originalFilename, savedFileName);
            String sqlContent = new String(Files.readAllBytes(filePath));
            List<TableSchema> schemas = SqlParserUtil.extractAllSchemas(sqlContent);


            // 保存属性到 attributessets 表
            for (TableSchema schema : schemas) {
                for (String attribute : schema.getAttributes()) {
                    attributessets attr = new attributessets();
                    attr.setAttributename(attribute);
                    attr.setDbid(db.getDbid());
                    int rowsAffected = am.insert(attr);
                    logger.info("插入属性：{}，影响行数：{}", attribute, rowsAffected);
                }
            }

            Map<String, Object> data = new HashMap<>();
            data.put("savedPath", filePath.toString());
            data.put("dbName", db.getDbname());
            data.put("dbId", db.getDbid());

            return Result.ok().message("文件上传成功").data("data",data);

        } catch (IOException e) {
            logger.error("文件上传失败: {}", e.getMessage(), e);
            return Result.error().message("文件上传失败：" + e.getMessage()).code(Result.ERROR);
        } catch (Exception e) {
            logger.error("系统错误: {}", e.getMessage(), e);
            return Result.error().message("系统错误").code(Result.ERROR);
        }
    }
    public Result setuploadSQLFile(MultipartFile file,int DBid) {
        // User user = getuser(token);
        Db db = new Db();
        //db.setUserid(user.getId());

        try {
            if (file.isEmpty()) {
                return Result.error().message("上传文件不能为空").code(Result.ERROR);
            }

            File uploadPath = new File(UPLOAD_DIR);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }

            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String dbNameWithoutExtension = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            db.setDbname(dbNameWithoutExtension);

            dm.insert(db);
            Subsetdb setdb=new Subsetdb();// 新建修复检查关系
            setdb.setDbid(DBid);
            setdb.setSetdbid(db.getDbid());
            sm.insert(setdb);

            String savedFileName = db.getDbid() + fileExtension;

            Path uploadDirectoryPath = Paths.get(UPLOAD_DIR);
            Path filePath = uploadDirectoryPath.resolve(savedFileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            logger.info("文件上传成功：{} -> {}", originalFilename, savedFileName);
            String sqlContent = new String(Files.readAllBytes(filePath));
            List<TableSchema> schemas = SqlParserUtil.extractAllSchemas(sqlContent);


            // 保存属性到 attributessets 表
            for (TableSchema schema : schemas) {
                for (String attribute : schema.getAttributes()) {
                    attributessets attr = new attributessets();
                    attr.setAttributename(attribute);
                    attr.setDbid(db.getDbid());
                    int rowsAffected = am.insert(attr);
                    logger.info("插入属性：{}，影响行数：{}", attribute, rowsAffected);
                }
            }

            Map<String, Object> data = new HashMap<>();
            data.put("savedPath", filePath.toString());
            data.put("dbName", db.getDbname());
            data.put("dbId", db.getDbid());
            data.put("setid",setdb.getSetid());

            return Result.ok().message("文件上传成功").data("data",data);

        } catch (IOException e) {
            logger.error("文件上传失败: {}", e.getMessage(), e);
            return Result.error().message("文件上传失败：" + e.getMessage()).code(Result.ERROR);
        } catch (Exception e) {
            logger.error("系统错误: {}", e.getMessage(), e);
            return Result.error().message("系统错误").code(Result.ERROR);
        }
    }
}
